import plupload from '../../static/plupload-2.1.2/js/plupload.full.min.js'

const serverUrl = 'http://www.edumavin.com:8080/api/oss/postpolicy'
const ossUrl = 'http://oss.aliyuncs.com'
let ossFile = ''
let message = ''
let expire = 0
let now = 0
let host = ''
let policyBase64 = ''
let accessid = ''
let signature = ''
let callbackbody = ''
let key = ''
let g_object_name_type = ''
let g_object_name = ''

const fileUpload = (obj,callback)=>{
	upload()
	function sendRequest() {
		const xmlhttp = new XMLHttpRequest();
		// 你的服务端接口地址:  参考demo:http://oss-demo.aliyuncs.com/oss-h5-upload-js-php/
		// 服务端签名后直传文档:  https://help.aliyun.com/document_detail/31926.html
		xmlhttp.open('GET', serverUrl, false);
		xmlhttp.send(null);
		return xmlhttp.responseText;
	}
	function getSignature() {
		// 可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
		now = Date.parse(new Date()) / 1000;
		if (expire < now + 3) {
			const body = sendRequest();
			const e = eval;
			const obj = e(`(${body})`);
			const policy = obj.postpolicy;
			host = policy.host;
			policyBase64 = policy.policy;
			accessid = policy.accessid;
			signature = policy.signature;
			expire = parseInt(policy.expire, 10);
			callbackbody = policy.callback;
			key = policy.dir;
			return true;
		}
		return false;
	}
	function checkObjectRadio() {
		g_object_name_type = 'random_name';
	}
	function randomString(len = 32) {
		const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		const maxPos = chars.length;
		let pwd = '';
		for (let i = 0; i < len; i += 1) {
			pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	}
	function getSuffix(filename) {
		const pos = filename.lastIndexOf('.');
		let suffix = '';
		if (pos !== -1) {
			suffix = filename.substring(pos);
		}
		return suffix;
	}
	function calculateObjectName(filename) {
		if (g_object_name_type === 'local_name') {
			g_object_name += `${filename}`;
		} else if (g_object_name_type === 'random_name') {
			const suffix = getSuffix(filename);
			g_object_name = key + randomString(10) + suffix;
		}
		return '';
	}
	function getUploadedObjectName(filename) {
		if (g_object_name_type === 'local_name') {
			let tmpName = g_object_name;
			tmpName = tmpName.replace(`${filename}`, filename);
			return tmpName;
		} else if (g_object_name_type === 'random_name') {
			return g_object_name;
		}
		return '';
	}
	function setUploadParam(up, filename, ret) {
		if (ret === false) {
			getSignature();
		}
		g_object_name = key;
		if (filename !== '') {
			calculateObjectName(filename);
		}
		const newMultipartParams = {
			key: g_object_name,
			policy: policyBase64,
			OSSAccessKeyId: accessid,
			// 让服务端返回200,不然，默认会返回204
			success_action_status: '200',
			signature: signature,
			callback: callbackbody,
		};
		up.setOption({
			url: host,
			multipart_params: newMultipartParams,
		});
		up.start();
	}
	function upload() {
		const uploader = new plupload.Uploader({
			runtimes: 'html5,flash,silverlight,html4',
			multi_selection: false,
			flash_swf_url: '../../../../static/plupload-2.1.2/js/Moxie.swf',
			silverlight_xap_url: '../../../../static/plupload-2.1.2/js/Moxie.xap',
			url: ossUrl,
			init: {
				PostInit: () => {
					ossFile = '';
					setUploadParam(uploader, '', false);
				},
				FilesAdded: (up, files) => {
					console.log('File added successfully')
				},
				BeforeUpload: (up, file) => {
					checkObjectRadio();
					up.addFile(obj.file)
					setUploadParam(up, file.name, true);
				},
				UploadProgress: (up, file) => {
					if(file.percent < 100){
						console.log('上传中...')
					}else if(file.percent == 100){
						console.log('上传完毕')
					}
				},
				FileUploaded: (up, file, info) => {
					if (info.status === 200) {
						const e = eval;
						const obj = e(`(${info.response})`);
						this.$emit('setVideoUrl', obj.fileurl);
						//document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML
						//= 'upload to oss success, object name:' + this.getUploadedObjectName(file.name) + ' 回调服务器返回的内容是:' + info.response;
					} else {
						document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
					}
				},
				Error: (up, err) => {
					console.log('上传失败')
				},
			},
		});
		uploader.init();
		uploader.addFile(obj.file)
	}
}

export {fileUpload}